package com.fottas.adware.payment.action;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.fottas.adware.common.api.IErrorCode;
import com.fottas.adware.common.emun.PayTypeEnum;
import com.fottas.adware.common.exception.ApiException;
import com.fottas.adware.payment.model.vo.request.PayRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service("aliPayAction")
public class AliPayAction implements PayAction {

    @Override
    public String doAction(PayRequest request) {
        try {
            AlipayTradeAppPayResponse response = Factory
                    .Payment
                    .App()
                    .pay(request.getSubject(), request.getOutTradeNo(), request.getTotalFee());
            if (!ResponseChecker.success(response)) {
                log.error("支付宝App支付(系统)失败,request:{},response:{}", request, response);
                throw ApiException.create(IErrorCode.ALIPAY_PAY_FAILED);
            }
            return response.getBody();
        } catch (Exception e) {
            log.error("支付宝App支付(系统)链路异常,request:{},error:{}", request, ExceptionUtil.getMessage(e));
            throw ApiException.create(IErrorCode.FAILED);
        }
    }

    @Override
    public PayTypeEnum getPayType() {
        return PayTypeEnum.ALI;
    }
}
